<template>
  <a-modal
    :open="visible"
    :title="isEdit ? '编辑服务商' : '新增服务商'"
    width="800px"
    :footer="null"
    @cancel="handleCancel"
    @update:open="$emit('update:visible', $event)"
    class="service-provider-edit-modal"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      layout="vertical"
      @finish="handleSubmit"
    >
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="服务商名称" name="providerName">
            <a-input
              v-model:value="formData.providerName"
              placeholder="请输入服务商名称"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="服务商类型" name="providerType">
            <a-select
              v-model:value="formData.providerType"
              placeholder="请选择服务商类型"
            >
              <a-select-option value="PAYMENT">支付服务商</a-select-option>
              <a-select-option value="TECH">技术服务商</a-select-option>
              <a-select-option value="INTEGRATED">综合服务商</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="联系人" name="contactPerson">
            <a-input
              v-model:value="formData.contactPerson"
              placeholder="请输入联系人"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="联系电话" name="contactPhone">
            <a-input
              v-model:value="formData.contactPhone"
              placeholder="请输入联系电话"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="联系邮箱" name="contactEmail">
            <a-input
              v-model:value="formData.contactEmail"
              placeholder="请输入联系邮箱"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="备注" name="remark">
            <a-textarea
              v-model:value="formData.remark"
              placeholder="请输入备注信息"
              :rows="4"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="状态" name="status">
            <a-select
              v-model:value="formData.status"
              placeholder="请选择状态"
            >
              <a-select-option :value="1">启用</a-select-option>
              <a-select-option :value="0">禁用</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <div class="form-actions">
        <a-space>
          <a-button @click="handleCancel">取消</a-button>
          <a-button
            type="primary"
            html-type="submit"
            :loading="submitting"
          >
            {{ isEdit ? '更新' : '创建' }}
          </a-button>
        </a-space>
      </div>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import type { ServiceProvider } from '@/mock/service-providers'

// Props
interface Props {
  visible: boolean
  serviceProvider?: ServiceProvider | null
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  serviceProvider: null
})

// Emits
const emit = defineEmits<{
  'update:visible': [visible: boolean]
  'success': [data: ServiceProvider]
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)

// 表单数据
const formData = reactive({
  providerId: '',
  providerName: '',
  providerType: '',
  contactPerson: '',
  contactPhone: '',
  contactEmail: '',
  remark: '',
  status: 1
})

// 表单验证规则
const rules = {
  providerName: [
    { required: true, message: '请输入服务商名称', trigger: 'blur' },
    { min: 2, max: 50, message: '服务商名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  providerType: [
    { required: true, message: '请选择服务商类型', trigger: 'change' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  contactEmail: [
    { required: true, message: '请输入联系邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 计算属性
const isEdit = computed(() => !!props.serviceProvider)

// 方法
const resetForm = () => {
  Object.assign(formData, {
    providerId: '',
    providerName: '',
    providerType: '',
    contactPerson: '',
    contactPhone: '',
    contactEmail: '',
    remark: '',
    status: 1
  })
  formRef.value?.clearValidate()
}

// 监听服务商数据变化
watch(
  () => props.serviceProvider,
  (newVal) => {
    if (newVal) {
      // 编辑模式，填充表单数据
      Object.assign(formData, {
        providerId: newVal.providerId,
        providerName: newVal.providerName,
        providerType: newVal.providerType,
        contactPerson: newVal.contactPerson,
        contactPhone: newVal.contactPhone,
        contactEmail: newVal.contactEmail,
        remark: '',
        status: newVal.status
      })
    } else {
      // 新增模式，重置表单
      resetForm()
    }
  },
  { immediate: true }
)

const handleCancel = () => {
  emit('update:visible', false)
  resetForm()
}

const handleSubmit = async () => {
  try {
    submitting.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    const result: ServiceProvider = {
      id: Date.now(),
      providerId: formData.providerId || `SP${Date.now()}`,
      providerName: formData.providerName,
      providerType: formData.providerType as 'PAYMENT' | 'TECH' | 'INTEGRATED',
      contactPerson: formData.contactPerson,
      contactPhone: formData.contactPhone,
      contactEmail: formData.contactEmail,
      merchantCount: 0,
      channelConfigs: [],
      status: formData.status,
      createdTime: new Date().toLocaleString()
    }

    message.success(`${isEdit.value ? '更新' : '创建'}服务商成功`)
    emit('success', result)
    emit('update:visible', false)
    resetForm()
  } catch (error) {
    message.error(`${isEdit.value ? '更新' : '创建'}服务商失败`)
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.service-provider-edit-modal :deep(.ant-modal-body) {
  padding: 24px;
}

.form-actions {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
}
</style>